import React, { useEffect, useState } from 'react';
import { fetchPostDetail, updatePost, deletePost, fetchComments, createComment, updateComment, deleteComment } from '../api';
import { useParams, useNavigate } from 'react-router-dom';

interface Comment {
  id: number;
  content: string;
  // 可选：author?: { name: string };
}

interface Post {
  id: number;
  title: string;
  content: string;
  comments?: Comment[];
}

const PostDetail: React.FC = () => {
  const { postId } = useParams();
  const navigate = useNavigate();
  const [post, setPost] = useState<Post | null>(null);
  const [editMode, setEditMode] = useState(false);
  const [title, setTitle] = useState('');
  const [content, setContent] = useState('');
  const [comments, setComments] = useState<Comment[]>([]);
  const [editingCommentId, setEditingCommentId] = useState<number | null>(null);
  const [editingCommentContent, setEditingCommentContent] = useState('');

  const load = () => {
    if (postId) {
      fetchPostDetail(postId).then(res => {
        let data = res.data?.data || res.data;
        setPost(data);
        setTitle(data?.title || '');
        setContent(data?.content || '');
      });
      fetchComments(postId).then(res => {
        let data = res.data?.data || res.data;
        setComments(Array.isArray(data) ? data : []);
      });
    }
  };

  useEffect(() => {
    load();
    // eslint-disable-next-line
  }, [postId]);

  const handleUpdate = async () => {
    if (postId) {
      await updatePost(postId, { title, content });
      setEditMode(false);
      load();
    }
  };

  const handleDelete = async () => {
    if (postId && window.confirm('确定要删除该帖子吗？')) {
      await deletePost(postId);
      navigate(-1);
    }
  };

  // 评论相关
  const handleAddComment = async (commentContent: string) => {
    if (postId && commentContent.trim()) {
      await createComment({ content: commentContent, postId });
      load(); // 发表评论后刷新
    }
  };

  const handleEditComment = (comment: Comment) => {
    setEditingCommentId(comment.id);
    setEditingCommentContent(comment.content);
  };

  const handleUpdateComment = async () => {
    if (editingCommentId && editingCommentContent.trim()) {
      await updateComment(editingCommentId.toString(), { content: editingCommentContent });
      setEditingCommentId(null);
      setEditingCommentContent('');
      load();
    }
  };

  const handleDeleteComment = async (commentId: number) => {
    if (window.confirm('确定要删除该评论吗？')) {
      await deleteComment(commentId.toString());
      load();
    }
  };

  return (
    <div>
      {post && (
        <>
          <div style={{ marginBottom: 24 }}>
            {editMode ? (
              <>
                <input value={title} onChange={e => setTitle(e.target.value)} placeholder="帖子标题" />
                <textarea value={content} onChange={e => setContent(e.target.value)} placeholder="帖子内容" />
                <button onClick={handleUpdate}>保存</button>
                <button onClick={() => setEditMode(false)}>取消</button>
              </>
            ) : (
              <>
                <h2>{post.title}</h2>
                <div style={{ color: '#666', marginBottom: 8 }}>{post.content}</div>
                <button onClick={() => setEditMode(true)}>编辑帖子</button>
                <button onClick={handleDelete} style={{ marginLeft: 8, background: '#e53e3e' }}>删除帖子</button>
              </>
            )}
          </div>
          <div>
            <h4>评论</h4>
            <CommentInput onSubmit={handleAddComment} />
            <ul style={{ paddingLeft: 0 }}>
              {comments.map(c => (
                <li key={c.id} style={{ marginBottom: 10, background: '#f8fafc', borderRadius: 5, padding: 10 }}>
                  {editingCommentId === c.id ? (
                    <>
                      <textarea value={editingCommentContent} onChange={e => setEditingCommentContent(e.target.value)} />
                      <button onClick={handleUpdateComment}>保存</button>
                      <button onClick={() => setEditingCommentId(null)}>取消</button>
                    </>
                  ) : (
                    <>
                      <span>{c.content}</span>
                      <button style={{ marginLeft: 10 }} onClick={() => handleEditComment(c)}>编辑</button>
                      <button style={{ marginLeft: 6, background: '#e53e3e' }} onClick={() => handleDeleteComment(c.id)}>删除</button>
                    </>
                  )}
                </li>
              ))}
            </ul>
          </div>
        </>
      )}
    </div>
  );
};

// 评论输入框组件
const CommentInput: React.FC<{ onSubmit: (content: string) => void }> = ({ onSubmit }) => {
  const [content, setContent] = useState('');
  return (
    <div style={{ marginBottom: 16 }}>
      <textarea value={content} onChange={e => setContent(e.target.value)} placeholder="写评论..." />
      <button onClick={() => { onSubmit(content); setContent(''); }}>评论</button>
    </div>
  );
};

export default PostDetail;